//
//  LPFStatusPictureView.swift
//  WeiBo
//
//  Created by mac on 16/4/20.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

// cell 重用标识
private let LPFStatusPictureViewCellId = "LPFStatusPictureViewCellId"

// cell 间距
private let itemMargin: CGFloat = 5
// cell 的宽高
private let cellWH: CGFloat = (SCREENW - 20 - itemMargin * 2) / 3

class LPFStatusPictureView: UICollectionView {
    
    var pictureInfo: [LPFPictureInfoModel]?{
        didSet{
            countLabel.text = "\(pictureInfo?.count ?? 0)"
            let size = getPictureViewSize(pictureInfo?.count ?? 0)
            
            // 更改自己的约束 没有涉及到被人来约束的 需要使用update 更简单
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            
            // 得到数据后 记得刷新
            self.reloadData()
        }
    }
    
    // 处理我们的配图size
    func getPictureViewSize(count: Int) -> CGSize{
        // 列数 和行数
        let col = count >= 3 ? 3 : count
        let row = (count - 1) / 3 + 1
        
        // 配图的宽高
        let width = CGFloat(col) * cellWH + CGFloat(col - 1) * itemMargin
        let height = CGFloat(row) * cellWH + CGFloat(row - 1) * itemMargin
        return CGSize(width: width, height: height)
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
    }

    
    
    // MARK: - 设置视图
    private func setupUI(){
        // 由于该控件原创微博和转发微博都需要使用 所以需要设置成透明色
        self.backgroundColor = UIColor.clearColor()
        
        // 设置数据源方法
        dataSource = self
        
        //代理
        delegate = self
        
        //注册cell
        registerClass(LPFStatusPictureViewCell.self, forCellWithReuseIdentifier: LPFStatusPictureViewCellId)
        
        // 设置layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // 设置itemSiz
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置垂直和水平间距
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        
        //添加控件
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
    }
    // MARK: - 懒加载控件
    private lazy var countLabel: UILabel = UILabel(textColor: UIColor.redColor(), textFont: 34)
    
}

// MARK: - 数据源, 代理
extension LPFStatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfo?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LPFStatusPictureViewCellId, forIndexPath: indexPath) as! LPFStatusPictureViewCell
        
        cell.pic = pictureInfo![indexPath.item]
        
        return cell
    }
    
    //点击方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let browser = SDPhotoBrowser()
        //原图的父控件
        browser.sourceImagesContainerView = self
        //原图的数量
        browser.imageCount = pictureInfo?.count ?? 0
        //当前需要展示的图片的index
        browser.currentImageIndex = indexPath.item
        //代理
        browser.delegate = self
        //展示图片浏览器
        browser.show()
    }
}

// MARK: - 自定义cell
class LPFStatusPictureViewCell: UICollectionViewCell{
    var pic: LPFPictureInfoModel?{
        didSet{
            
            bgImageView.sd_setImageWithURL(NSURL(string: pic?.thumbnail_pic ?? ""),placeholderImage: UIImage(named: "timeline_card_top_background"))
            
            if let p = pic?.thumbnail_pic where p.hasSuffix(".gif"){
                gifImageView.hidden = false
            }else{
                gifImageView.hidden = true
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        self.backgroundColor = UIColor.whiteColor()
        
        
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.bottom.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载控件
    //背景图片
    private lazy var bgImageView: UIImageView = {
        let img = UIImageView(image: UIImage(named: "timeline_card_top_background"))
        img.contentMode = .ScaleAspectFill
        img.clipsToBounds = true
        return img
    }()
    //动态图片logo
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
}

// MARK: - 图片浏览器代理方法
extension LPFStatusPictureView: SDPhotoBrowserDelegate{
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = pictureInfo![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlString)
    }
    //获取小图方法 不建议
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = self.cellForItemAtIndexPath(indexPath) as! LPFStatusPictureViewCell
        return cell.bgImageView.image
    }
}
